<?php

namespace App\Models\Landscaping;

use Grimzy\LaravelMysqlSpatial\Types\Point;
use Grimzy\LaravelMysqlSpatial\Types\Polygon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Grimzy\LaravelMysqlSpatial\Eloquent\SpatialTrait;
use App\Models\Landscaping\ParkVegetationFile;

class ParkVegetation extends Model
{
    use SoftDeletes;
    use SpatialTrait;
    protected $guarded = ['virescence_ids'];
    protected $spatialFields = ['location','areas'];

    public function getList($request)
    {
        $per_page = $request->input('per_page',10);
        return self::orderBy('id','desc')
                ->with(['vegetation','landscaping','files'])
                ->whereHas('landscaping',function($query) use ($request){
                    //检测当前的请求中是否包含park_name参数
                    $park_name = $request->input('park_name', '');
                    if(!empty($park_name)) {
                        $query->where('park_name','like','%'.$park_name.'%');
                    }
                })
                ->where(function($query) use ($request){
                    //检测当前的请求中是否包含vegetation_name参数
                    $vegetation_name = $request->input('vegetation_name', '');
                    $location = $request->input('location','');
                    $areas = $request->input('areas','');
                    if(!empty($vegetation_name)) {
                        $query->where('name','like','%'.$vegetation_name.'%');
                    }
                    if(!empty($location)) {
                        $location = Point::fromString($location);
                        $query->distance('location', $location, 10);
                    }
                    if(!empty($areas)) {
                        $areas = Polygon::fromString($areas);
                        $query->distance('areas', $areas, 10);
                    }
                })
                ->paginate($per_page);
    }

    //获取植被种类信息
    public function vegetation()
    {
    	return $this->belongsTo(\App\Models\Landscaping\Vegetation::class,'vegetation_id','id')->select('id','name');
    }

    //查看园林信息
    public function landscaping()
    {
        return $this->belongsTo(\App\Models\Landscaping\Landscaping::class,'landscaping_id','id')->select('id','park_name','park_number','yh_areas','level');
    }

    public function files()
    {
        return $this->hasMany(ParkVegetationFile::class,'v_id')->with('file');
    }
}
